<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 商户通行证函数库
 * 
 * @desc 虽然目录不同，但名称也不能相同，否则只能挂载一次！
 * @version 1.0.0 
 * @author  Jason
 * @date	2017年5月11日 下午5:39:13
 * 
 */
class Lib_passport_merchant
{
	/**
	 * Current CI instance object
	 * 
	 * @desc CI_Controller::get_instance();
	 * @var CI_Controller $CI
	 */
	private $CI;
	
	public function __construct()
	{
		$this->CI =& get_instance();
		
		$this->CI->load->database();
		$this->CI->load->model('mod_member');
	}
	
	
	/**
	 * 商户用户登录处理器
	 *
	 * @method  POST
	 * @author  Jason
	 * @date	2017年5月11日 下午5:12:38
	 * @param   $name, $password
	 *
	 * @return  [<status>, <content>]	一个两元素数组，第一个元素表示状态，第二个表示相应内容
	 * 	        eg:	[true, <userData>]
	 * 				[false, <errorMesg>]
	 */
	public function business_login()
	{
		$this->CI->load->library('form_validation');
		
		$status = false;
		$content = ['error'];
		if(FALSE === $this->CI->form_validation->run('login')) {
			$errorKey = $this->CI->form_validation->error_array();
			$status = false;
			$content = $errorKey;
		} else {
			$data = $this->CI->input->post();
			$name = $data['name'];
			$password = $data['password'];
			$member = $this->CI->mod_member->get_member_by_login($name, $password);
			if (!empty($member['id'])) {
				$status = true;
				$content = $member;
				$this->CI->config->load('dbconst');
				$merchant_role_id = $this->CI->config->item('merchant_owner', 'role_id');
				$status_tags = $this->CI->mod_member->calculate_status_tags($member['status'], 'negative');
				if (in_array('disabled', $status_tags)) {
					$status = false;
					$content = ['passport_msg_member_status_disabled'];
				} else if (empty($member['role_id']) || $member['role_id'] !== $merchant_role_id) {
					$status = false;
					$content = ['passport_msg_member_role_not_merchant'];
				}
			} else {
				// passport_msg_login_faild
				$content = [];
			}
		}
		
		return [$status, $content];
	}
	
	
	public function get_preferences($member_id)
	{
		$preferences = $this->CI->mod_member->get_member_preferences($member_id);
		$preferences = array_merge([
				'language' => 'english',
				'currency' => 'USD',
				'timezone' => 'UTC',
		], $preferences);
		
		return $preferences;
	}
	
	public function set_preferences($member_id, $preferences)
	{
		// 改库
		$this->CI->mod_member->set_member_preferences($member_id, $preferences);
	}
	
}